package cn.it.config;

import cn.it.anno.MyAutowired;
import cn.it.anno.MyComponent;
import cn.it.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@MyComponent
public class ProxyFactory {

    @MyAutowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;
                        try {
                            transactionManager.begin();
                            result = method.invoke(obj, args);
                            transactionManager.commit();
                        } catch (Exception e) {
                            transactionManager.rollback();
                            throw new Exception("error!!!!", e);
                        }
                        return result;
                    }
                }
        );
    }

    public Object getCglibProxy(Object obj) {
        Enhancer enhancer = new Enhancer();
        return enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try {
                    transactionManager.begin();
                    result = method.invoke(obj, objects);
                    transactionManager.commit();
                } catch (Exception e) {
                    transactionManager.rollback();
                    throw new Exception("error!!!!", e);
                }
                return result;
            }
        });
    }
}
